package com.etone.smartAudit.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etone.smartAudit.domain.PLogVersion;
import com.etone.smartAudit.domain.PPushLog;
import com.etone.smartAudit.dto.PortalPushDTO;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.PLogVersionMapper;
import com.etone.smartAudit.mapper.PPushLogMapper;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/***
 * port推送代办
 */
@Slf4j
@Service
public class PPushLogService extends ServiceImpl<PPushLogMapper, PPushLog> {


    /***
     * 最大失败次数
     */
    @Value("${uds.maxFailCount:3}")
    private Integer maxFailCount;

    /***
     * 最多获取失败次数重复的数量
     */
    @Value("${uds.maxFailCount:10}")
    private Integer getFailCount;

    @Lazy
    @Autowired
    private PortalPushService portalPushService;

    /***
     * 添加日志
     * @param version
     */
    public void add(PPushLog version) {
        this.save(version);
    }

    /***
     * 添加日志
     * @param msg
     */
    public PPushLog add(PortalPushDTO dto, String msg) throws Exception {
        Integer logId = dto.getPushLogId();
        if (logId != null) {
            //更新日志记录
            PPushLog pushLog = this.getById(logId);
            if (pushLog == null) {
                throw new Exception("日志文件不存在");
            }
            pushLog.setModifyTime(new Date());
            pushLog.setMsg(msg);
            //默认为失败
            pushLog.setOptionSuccess(false);
            if (!pushLog.getOptionSuccess()) {
                pushLog.setFailTimes((pushLog.getFailTimes() == null ? 0 : pushLog.getFailTimes()) + 1);
            }
            this.updateById(pushLog);
            return pushLog;
        } else {
            //添加到日志文件
            PPushLog pushLog = new PPushLog();
            pushLog.setOptionSuccess(false);
            pushLog.setBusiness(dto.getBusiness());
            pushLog.setFailTimes(0);
            pushLog.setSeqno(dto.getSeqno());
            pushLog.setInserttime(new Date());
            pushLog.setModifyTime(new Date());
            pushLog.setMsg(msg);
            this.save(pushLog);
            return pushLog;
        }

    }

    /***
     * 更新日志
     * @param version
     * @return
     */
    public boolean edit(PPushLog version) {
        Integer id = version.getId();
        if (id == null) {
            log.error("id不能为空");
            return false;
        }
        PPushLog data = getById(id);
        data.setModifyTime(new Date());
        data.setMsg(version.getMsg());

        data.setOptionSuccess(version.getOptionSuccess());
        if (!data.getOptionSuccess()) {
            data.setFailTimes((data.getFailTimes() == null ? 0 : data.getFailTimes()) + 1);
        }
        return this.updateById(data);
    }

    /***
     * 处理为成功状态
     * @param pushLog
     * @return
     */
    public boolean success(PPushLog pushLog) {
        pushLog.setOptionSuccess(true);
        return this.updateById(pushLog);
    }

    /***
     * 异步持续同步失败的推送
     */
    @Async
    public void sygnFaiLog() {
        LambdaQueryWrapper<PPushLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PPushLog::getOptionSuccess, false);
        queryWrapper.lt(PPushLog::getFailTimes, maxFailCount + 1);
        queryWrapper.last(" limit " + getFailCount);

        List<PPushLog> list = this.list(queryWrapper);
        list.stream().forEach(plog -> {
            try {
                portalPushService.push(plog);
                Thread.sleep(2000);
            } catch (Exception e) {
                log.error("处理错误", e);
            }
        });

    }
}
